package com.carhailing.coupons.utils;

import com.carhailing.common.domain.coupons.CouponsVo;
import com.carhailing.coupons.constant.CouponActivityKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.carhailing.coupons.constant.CouponCacheKeyConstant.getCouponActivityKey;

/**
 * redis工具类
 */
@Component
public class CouponRedisLuaUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public boolean receive(CouponsVo couponsVo) {
        // 领券分多步操作
        //1.扣减领券活动库存，
        // 如果失败，则回滚扣减领券活动库存
        // 如果成功 返回最新库存数量
        String script = "local newTotalNumber = redis.call('HINCRBY', KEYS[1], KEYS[2], -ARGV[1]); " +
                "if (newTotalNumber < 0) then " +
                "redis.call('HINCRBY', KEYS[1], KEYS[2], ARGV[1]); return -1; " +
                "else return newTotalNumber end;";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript();
        redisScript.setScriptText(script);
        List<String> keys = new ArrayList<>();
        keys.add(getCouponActivityKey(Long.valueOf(couponsVo.getCouponId())));
        keys.add(CouponActivityKeyConstant.TOTAL_NUMBER);
        redisScript.setResultType(Long.class);
        Long totalNumber = (Long) redisTemplate.execute(redisScript, keys, String.valueOf(couponsVo.getCouponsTotal()));
        return totalNumber != null && totalNumber > -1;


    }


}
